<script setup lang="ts">
import type { SysSettings, SysSettingsQuery } from '@/apis/system/sysSettingApi'

import type { DataAction } from '@/components/DataForm/types'

import { Search } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { sysSettingsApi } from '@/apis/system/sysSettingApi'
import { doDataAction } from '@/components/DataForm/types'
import { useTable } from '@/components/DataPage/useTable'
import BaseCard from '@/layouts/BaseCard.vue'
import { hasAnyAuth } from '@/utils/authUtil'
import SysSettingsDataForm from './SysSettingsDataForm.vue'
import SysSettingsDesignDialog from './SysSettingsDesignDialog.vue'

const designFormRef = ref<InstanceType<typeof SysSettingsDesignDialog>>()
const currentRowKey = ref<number>()
const {
  queryFormData,

  submitQuery,
  Table,
} = useTable<SysSettingsQuery, SysSettings>({
  autoQuery: true,
  queryPage: sysSettingsApi.queryPage,
  tableFields: [
    { title: 'ID', name: 'id', width: 80, columnType: 'KEY', sort: true, show: false },
    { title: '名称', name: 'name', width: 90, sort: false },
  ],
})

const settingData = ref<SysSettings>()
const settingDataEditing = ref(false)
const dataFormRef = ref<InstanceType<typeof SysSettingsDataForm>>()
async function onSetting(row: SysSettings) {
  settingData.value = await sysSettingsApi.findDetail(row.id!)
  settingDataEditing.value = false
  currentRowKey.value = row.id
}

async function onSettingDataSubmit() {
  await dataFormRef.value?.submit()
  settingDataEditing.value = false
}

async function onSubmitDesignSuccess(title: string, data: any) {
  await submitQuery(title === '新增' ? 0 : undefined)
  await onSetting(data)
  settingDataEditing.value = true
}

const actions = reactive<Record<string, DataAction>>({
  create: {
    label: '新增',
    type: 'primary',
    authCode: 'system:settings:create',
    click: () => designFormRef.value?.open('新增', { state: 'ENABLE' }, sysSettingsApi.create),
  },
  modify: {
    label: '编辑',
    authCode: 'system:settings:modify',
    click: row => designFormRef.value?.open('编辑', row, sysSettingsApi.modify),
  },
  changeState: {
    label: row => row.state === 'ENABLE' ? '禁用' : '启用',
    authCode: 'system:settings:modify',
    confirm: row => `是否${row.state === 'ENABLE' ? '禁用' : '启用'}设置`,
    click: async (data) => {
      if (data.id !== settingData.value?.id) {
        await onSetting(data)
      }
      const state = data.state === 'ENABLE' ? 'DISABLE' : 'ENABLE'
      try {
        if (state === 'ENABLE') {
          await dataFormRef.value?.validate()
        }
        await sysSettingsApi.modify({ id: data.id, state })
      }
      catch {
        settingDataEditing.value = true
        ElMessage.error(`${state === 'ENABLE' ? '启用' : '禁用'}失败,请检查设置`)
        throw new Error(`${state === 'ENABLE' ? '启用' : '禁用'}失败`)
      }
    },
    success: () => submitQuery(),
    message: true,
  },
  remove: {
    label: '删除',
    authCode: 'system:settings:remove',
    confirm: '删除不可恢复，请谨慎确认',
    click: data => sysSettingsApi.remove(data.id),
    success: async () => {
      settingData.value = undefined
      settingDataEditing.value = false
      await submitQuery()
    },
    message: true,
  },
})
</script>

<template>
  <div class="h-full flex flex-row gap-2 overflow-hidden">
    <BaseCard title="列表">
      <template #buttons>
        <!-- 表格按钮 -->

        <el-input
          v-if="queryFormData"
          v-model="queryFormData.name"
          class="mx-1 max-w-50"
          placeholder="搜索"
          clearable
          :prefix-icon="Search"
        >
          <template #append>
            <el-button :icon="Search" @click="submitQuery(1)" />
          </template>
        </el-input>
        <data-button :action="actions.create" />
      </template>
      <!-- 数据表格 -->
      <Table :current-row-key="currentRowKey" @row-click="onSetting">
        <template #name="{ row }">
          <div class="flex flex-justify-between">
            <div class="flex">
              {{ row.name }}[{{ row.code }}]
            </div>
            <div v-if="hasAnyAuth('system:settings:modify')">
              <el-switch
                v-model="row.state"
                active-value="ENABLE"
                inactive-value="DISABLE"
                :before-change="async() => { await doDataAction(row, actions.changeState);return false }"
              />
            </div>
          </div>
        </template>
      </Table>
    </BaseCard>

    <BaseCard :title="`设置${settingData?.name ?? ''}`" class="flex-1">
      <template v-if="settingData !== undefined" #buttons>
        <el-button v-if="!settingDataEditing && hasAnyAuth('system:settings:modify')" type="default" @click="doDataAction(settingData, actions.modify)">
          编辑
        </el-button>
        <el-button v-if="!settingDataEditing && hasAnyAuth('system:settings:remove')" type="danger" @click="doDataAction(settingData, actions.remove)">
          删除
        </el-button>
        <el-button v-if="!settingDataEditing && hasAnyAuth('system:settings:modify')" type="primary" @click="settingDataEditing = true">
          设置
        </el-button>
        <el-button v-if="settingDataEditing" type="primary" @click="onSettingDataSubmit()">
          提交
        </el-button>
        <el-button v-if="settingDataEditing" type="info" @click="onSetting(settingData)">
          取消
        </el-button>
      </template>
      <SysSettingsDataForm
        v-if="settingData"
        ref="dataFormRef"
        class="overflow-scroll"

        :settings="settingData"
        :disabled="!settingDataEditing"
      />
    </BaseCard>
  </div>

  <SysSettingsDesignDialog ref="designFormRef" @success="onSubmitDesignSuccess" />
</template>
